package com.zhs.gccs.activity.gccs;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhs.gccs.R;
import com.zhs.gccs.adapter.GccsPeopleListAdapter;
import com.zhs.gccs.base.BaseActivity;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.vo.AdminPeopleBean;
import com.zhs.gccs.vo.AdminPeopleListBean;
import com.zhs.gccs.vo.XmGccsDeleteDataBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

public class AdminPersonActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    View iv_back;
    @BindView(R.id.tv_add)
    View tv_add;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    private int request_code_add = 100;

    private List<AdminPeopleBean> userList;
    private GccsPeopleListAdapter peopleListAdapter;


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getGccsUserList();
    }

    public static void start(Context context) {
        context.startActivity(new Intent(context, AdminPersonActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_person);
//        ImmersionBar.with(this).transparentBar().statusBarDarkFont(false).init();
//        ImmersionBar.with(this)
//                .statusBarColor(R.color.main_title_pressed_bg)
//                .statusBarDarkFont(false).init();
        ImmersionBar.with(this).transparentBar().statusBarDarkFont(false).init();
        ButterKnife.bind(this);
        llRoot.setPadding(0, ImmersionBar.getStatusBarHeight(this), 0, 0);

        userList = new ArrayList<>();
        peopleListAdapter = new GccsPeopleListAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(peopleListAdapter);
        peopleListAdapter.setOperationListener(new GccsPeopleListAdapter.ItemOperationListener() {
            @Override
            public void onDelete(AdminPeopleBean bean) {
                DialogUtils.showPromote2(context, "确认删除?", null, new DialogUtils.OnConfirmListener() {
                    @Override
                    public void onConfirmed() {
                        toDeleteData(bean);
                    }
                });
            }

            @Override
            public void onStop(AdminPeopleBean bean) {
                if("0".equals(bean.getStatus())){//0正常 1停用
                    DialogUtils.showPromote2(context, "确认停用?", null, new DialogUtils.OnConfirmListener() {
                        @Override
                        public void onConfirmed() {
                            toStopData(bean);
                        }
                    });
                }else {
                    DialogUtils.showPromote2(context, "确认启用?", null, new DialogUtils.OnConfirmListener() {
                        @Override
                        public void onConfirmed() {
                            toStartData(bean);
                        }
                    });
                }
            }

            @Override
            public void onItemClick(AdminPeopleBean bean) {
                Intent intent = new Intent(context,AdminPersonAddActivity.class);
                intent.putExtra(AdminPersonAddActivity.intent_data,bean);
                startActivityForResult(intent,request_code_add);
            }
        });

        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.top = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8F, Resources.getSystem().getDisplayMetrics());
                }
                outRect.bottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8F, Resources.getSystem().getDisplayMetrics());
                outRect.left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10F, Resources.getSystem().getDisplayMetrics());
                outRect.right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10F, Resources.getSystem().getDisplayMetrics());
            }
        });
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getGccsUserList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
//                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                getGccsUserList();
            }
        });

        initView();
        getGccsUserList();
    }

    private void initView() {
        iv_back.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        tv_add.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                Intent intent = new Intent(context,AdminPersonAddActivity.class);
                startActivityForResult(intent,request_code_add);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getGccsUserList();
    }

    private void getGccsUserList() {
        showDialog();
        toSubscribeSingleOb(Api.getDefault().getCjUsers(),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        AdminPeopleListBean bean = new Gson().
                                fromJson(result, AdminPeopleListBean.class);
                        userList.clear();
                        if (bean != null && bean.getCode() == 200 && bean.getData() != null&& bean.getData().size() >0 ) {
                            userList.addAll(bean.getData());
                            finishLoadMore();
                        }else {
                            finishLoadMore();
                        }
                        peopleListAdapter.setNewData(userList);
                    }

                    @Override
                    protected void _onError(String result) {
                        finishLoadMore();
                        refreshLayout.setEnableLoadMore(false);
                    }
                });
    }

    private void finishLoadMore() {
        dismissDialog();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    private void toDeleteData(AdminPeopleBean bean) {
        Map hashMap = new HashMap();
        hashMap.put("userName",bean.getUserName());
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().
                        deleteGccsUser(requestBody),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        XmGccsDeleteDataBean deleteDataBean = new Gson().fromJson(result, XmGccsDeleteDataBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (deleteDataBean != null && deleteDataBean.getCode() == 200) {
                            ToastUtils.toast("删除成功");
                            getGccsUserList();
                        } else {
                            ToastUtils.toast("删除失败");
                        }
                    }
                    @Override
                    protected void _onError(String result) {
                        Log.e("_onError",result);
                    }
                });
    }
    private void toStopData(AdminPeopleBean bean) {
        Map hashMap = new HashMap();
        hashMap.put("userName",bean.getUserName());
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().
                        stopGccsUser(requestBody),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        XmGccsDeleteDataBean deleteDataBean = new Gson().fromJson(result, XmGccsDeleteDataBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (deleteDataBean != null && deleteDataBean.getCode() == 200) {
                            ToastUtils.toast("停用成功");
                            getGccsUserList();
                        } else {
                            ToastUtils.toast("停用失败");
                        }
                    }
                    @Override
                    protected void _onError(String result) {
                        Log.e("_onError",result);
                    }
                });
    }
    private void toStartData(AdminPeopleBean bean) {
        Map hashMap = new HashMap();
        hashMap.put("userName",bean.getUserName());
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().
                        startGccsUser(requestBody),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        XmGccsDeleteDataBean deleteDataBean = new Gson().fromJson(result, XmGccsDeleteDataBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (deleteDataBean != null && deleteDataBean.getCode() == 200) {
                            ToastUtils.toast("停用成功");
                            getGccsUserList();
                        } else {
                            ToastUtils.toast("停用失败");
                        }
                    }
                    @Override
                    protected void _onError(String result) {
                        Log.e("_onError",result);
                    }
                });
    }

}
